package service

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"user-server/basic/config"
	"user-server/basic/pkg"
	__ "user-server/basic/proto"
	"user-server/handler/models"

	"github.com/mojocn/base64Captcha"
)

type Server struct {
	__.UnimplementedStreamGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}

	result, err := config.Rdb.Set(config.Ctx, "sendSms"+in.Phone, code, time.Minute*5).Result()
	if err != nil {
		return nil, err
	}
	if result != "" {
		return nil, errors.New("发送成功")
	}

	return &__.SendSmsResp{}, nil
}

func (s *Server) Captcha(_ context.Context, in *__.CaptchaReq) (*__.CaptchaResp, error) {

	c := base64Captcha.NewCaptcha(base64Captcha.DefaultDriverDigit, base64Captcha.DefaultMemStore)
	generate, s2, s3, err := c.Generate()
	if err != nil {
		return nil, err
	}

	fmt.Println(generate, s2, s3)

	config.Rdb.Set(config.Ctx, "captcha"+in.Phone, s3, time.Minute*3)

	return &__.CaptchaResp{
		CaptchaId: s2,
	}, nil
}

func (s *Server) GoodAdd(_ context.Context, in *__.GoodAddReq) (*__.GoodAddResp, error) {

	result, _ := config.Rdb.Get(config.Ctx, "sendSms"+in.Phone).Result()
	if result != in.SendCode {
		return nil, errors.New("短信错误")
	}
	result1, _ := config.Rdb.Get(config.Ctx, "captcha"+in.Phone).Result()
	if result1 != in.CaptchaCode {
		return nil, errors.New("图片验证错误")
	}
	good := models.Good{
		Phone:       in.Phone,
		Password:    pkg.Md5(in.Password),
		SendCode:    in.SendCode,
		CaptchaCode: in.CaptchaCode,
	}

	if err := good.GoodAdd(config.DB); err != nil {
		return nil, err
	}

	return &__.GoodAddResp{
		GoodId: int64(good.ID),
	}, nil
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {

	result, _ := config.Rdb.Get(config.Ctx, "sendSms"+in.Phone).Result()
	if result != in.SendCode {
		return nil, errors.New("短信错误")
	}
	result1, _ := config.Rdb.Get(config.Ctx, "captcha"+in.Phone).Result()
	if result1 != in.CaptchaCode {
		return nil, errors.New("图片验证错误")
	}

	var good models.Good

	if err := good.GoodLogin(config.DB, in.Phone); err != nil {
		return nil, errors.New("用户未注册")
	}

	return &__.LoginResp{
		GoodId: int64(good.ID),
	}, nil
}
